package com.hethongviet.job.helpers.download;

import java.io.BufferedInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import com.hethongviet.job.AppMain;
import com.hethongviet.job.Config;
import com.hethongviet.job.models.FileImage;

import android.annotation.TargetApi;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;

@TargetApi(3)
public class ImageLoadTask extends AsyncTask<String, Void, FileImage>
{
	private ImageView _imageView = null;
	private FileImage _imageFile = null;
	private ProgressBar _progressBar = null;
	private Activity _activity = null;
	public static int _errorCode = -1;

	public static final int STATUS_NONE = 0;
	public static final int ERROR_CONNECTION = 1;
	public static final int ERROR_URL_NOT_EXIST = 2;
	public static final int STATUS_SUCCESS = 3;
	public static final int ERROR_LOAD_DECODE_IMAGE = 4;

	public ImageLoadTask(Activity activity, ImageView imageView,
			FileImage imageFile, ProgressBar progressBar)
	{
		this._imageView = imageView;
		this._imageFile = imageFile;
		this._progressBar = progressBar;
		this._activity = activity;
		_errorCode = STATUS_NONE;
	}

	protected FileImage doInBackground(String... url)
	{
		FileImage imageFile = new FileImage();
		// ---download an image---
		Bitmap bitmap = null;
		try
		{
			bitmap = downloadImage(url[0]);
		} catch (IOException e1)
		{
			e1.printStackTrace();
		}
		try
		{
			Thread.sleep(3000);
		} catch (InterruptedException e)
		{
			e.printStackTrace();
		}
		imageFile.setBitmap(bitmap);
		return imageFile;
	}

	protected void onPostExecute(FileImage aImageFile)
	{
		if (_errorCode == ERROR_CONNECTION
				|| _errorCode == ERROR_LOAD_DECODE_IMAGE
				|| _errorCode == ERROR_URL_NOT_EXIST)
		{
			_activity.onWindowFocusChanged(true);
			_imageFile = null;
			return;
		}
		Bitmap bitmap = aImageFile.getBitmap();
		if (bitmap != null)
		{
			if (_imageView != null)
				_imageView.setImageBitmap(bitmap);
			_imageFile.setBitmap(bitmap);
			_imageView.setVisibility(View.VISIBLE);
			_progressBar.setVisibility(View.GONE);
			// _activity.onWindowFocusChanged(true);
			// LayoutParams layoutParams = new
			// LayoutParams(AppMain._imageFileView.getBitmap().getWidth(),
			// AppMain._imageFileView.getBitmap().getHeight());
			// layoutParams.gravity = Gravity.CENTER;
			// _imageView.setLayoutParams(layoutParams);
			// _imageView.invalidate();
		}
	}

	public Bitmap downloadImage(String url) throws IOException
	{
		Log.d("Debug", "11111111 download image: " + url);
		Bitmap bitmap = null;
		InputStream inputStream = null;
		InputStream inputStreamBuffered = null;
		try
		{
			// inputStreamBuffered = new OpenHttpConnection().get(url);
			inputStream = (new URL(url)).openStream();
			inputStreamBuffered = new BufferedInputStream(inputStream);

			Log.d("Debug", "11111111 download image inputstream: "
					+ inputStream);

			// First decode with inJustDecodeBounds=true to check dimensions
			final BitmapFactory.Options options = new BitmapFactory.Options();
			options.inJustDecodeBounds = true;
			BitmapFactory.decodeStream(inputStreamBuffered, null, options);

			Log.d("Debug", "11111111 download image BitmapFactory.Options1: "
					+ options);

			inputStream.close();
			inputStreamBuffered.close();

			// reconnect
			// inputStream = new OpenHttpConnection().get(url);
			inputStream = (new URL(url)).openStream();
			inputStreamBuffered = new BufferedInputStream(inputStream);

			Log.d("Debug", "11111111 download image reconnect inputstream: "
					+ inputStream);

			int sameSize = AppMain.getInSampleSize(options,
					Config.SCREEN_WIDTH, Config.SCREEN_HEIGHT);

			Log.d("Debug", "11111111 download image sameple size: " + sameSize);

			if (sameSize > 1)
			{
				Log.d("Debug", "11111111 download Get image scaled! ");
				// Decode bitmap with inSampleSize set final
				BitmapFactory.Options options1 = new BitmapFactory.Options();
				// Calculate inSampleSize options.inSampleSize =
				options1.inSampleSize = sameSize;
				options1.inJustDecodeBounds = false;

				Log.d("Debug",
						"11111111 download image get BitmapFactory.Options: "
								+ options1);

				bitmap = BitmapFactory.decodeStream(inputStreamBuffered, null,
						options1);

				Log.d("Debug", "11111111 download decodeStream success111 ");
			}
			else
			{
				Log.d("Debug", "11111111 download decodeStream ");
				bitmap = BitmapFactory.decodeStream(inputStreamBuffered);
				Log.d("Debug",
						"11111111 download decodeStream success222 bitmap = "
								+ bitmap);
			}

			inputStream.close();
			inputStreamBuffered.close();

			_errorCode = STATUS_NONE;
			if (bitmap == null)
			{
				Log.d("Debug", "11111111 download image ---null bitmap!!!");
				// downloadImage(url); redownload
				Log.d("Debug", "11111111 redownload");
				HttpURLConnection conn = (HttpURLConnection) (new URL(url)).openConnection();
				conn.setDoInput(true);
				conn.connect();
				conn.getContentLength();
				Log.d("Debug", "11111111 redownload conn.getContentLength() = " + conn.getContentLength());
				InputStream is = conn.getInputStream();

				bitmap = BitmapFactory.decodeStream(is);

				if (bitmap == null)
				{
					_errorCode = ERROR_LOAD_DECODE_IMAGE;
				}

			}
			else
			{
				_errorCode = STATUS_SUCCESS;
			}
		} catch (FileNotFoundException e)
		{
			/* Connection error */
			e.printStackTrace();
			bitmap = null;
			_errorCode = ERROR_URL_NOT_EXIST;

		} catch (Exception e)
		{
			/* URL not found */
			bitmap = null;
			e.printStackTrace();
			_errorCode = ERROR_CONNECTION;
		}

		return bitmap;
	}
}
